package com.topi.sharing.json;

import static com.topi.sharing.json.DateTimeSerializer.DATE_PATTERN;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;




import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

public class DateTimeDeserializer extends JsonDeserializer<Date> {

	
	@Override
	public Date deserialize(JsonParser jp, DeserializationContext ctxt)
														throws IOException
														, JsonProcessingException {
		
		JsonToken t = jp.getCurrentToken();
		
		SimpleDateFormat sdf =	new SimpleDateFormat(DATE_PATTERN);
		
		if (t ==  JsonToken.VALUE_NUMBER_INT ) {
			return new Date( jp.getLongValue() );
		}
		
		if (t == JsonToken.VALUE_STRING) {
			
			String str = jp.getText().trim();
			if (str.length() == 0) { // [JACKSON-360]
				return null;
			}
			
			try {
				return sdf.parse(str);
			} catch (ParseException e) {
				ctxt.mappingException(this.getClass());
			}
		}

		throw ctxt.mappingException(this.getClass());
	}
	
	
	public static void main(String[] args) throws ParseException {
		SimpleDateFormat sdf =	new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
		Date d = new Date ();
		System.out.println("" + sdf.format(d));
		Date dat = sdf.parse("2014-12-07 22:37:17 -02:00");
		System.out.println(dat);
	}

}
